package com.crm.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.crm.model.BaseModel;
import com.github.pagehelper.Page;
import com.lowagie.text.DocumentException;

public class ResponseUtil {
	public static void write(HttpServletResponse response, Object object) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println(object);
		out.flush();
		out.close();
	}

	public static void result(HttpServletResponse response, String result) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0L);
			response.getWriter().write(result);
			response.getWriter().flush();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * @Description : 返回页面page
	 * @author zealot
	 * @param @param
	 *            response
	 * @param @param
	 *            result
	 * @return void
	 * @version 创建时间 : 2016年11月1日 下午4:27:58
	 * @thorws
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void resultPage(HttpServletResponse response, HttpServletRequest request,
			Page<? extends BaseModel> list) {
		HashMap ajaxList = new HashMap();
		HashMap map = new HashMap();
		map.put("aaData", list.getResult());
		map.put("sEcho", request.getParameter("sEcho"));
		map.put("iTotalRecords", list.getTotal());
		map.put("iTotalDisplayRecords", list.getTotal());
		map.put("iDisplayLength", list.getPageSize());
		map.put("iDisplayStart", list.getPageNum());
		ajaxList.put("returnObject", map);
		result(response, JsonUtil.toJsonStr(ajaxList));
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void resultPageMap(HttpServletResponse response, HttpServletRequest request,
			Page<Map<String, Object>> list) {
		HashMap ajaxList = new HashMap();
		HashMap map = new HashMap();
		map.put("aaData", list.getResult());
		map.put("sEcho", request.getParameter("sEcho"));
		map.put("iTotalRecords", list.getTotal());
		map.put("iTotalDisplayRecords", list.getTotal());
		map.put("iDisplayLength", list.getPageSize());
		map.put("iDisplayStart", list.getPageNum());
		ajaxList.put("returnObject", map);
		result(response, JsonUtil.toJsonStr(ajaxList));
	}

	/**
	 * 
	 * @Description : excel文件导出
	 * @author zealot
	 * @param @param
	 *            wb
	 * @param @param
	 *            response
	 * @return void
	 * @version 创建时间 : 2016年11月15日 上午9:37:50
	 * @throws IOException
	 * @thorws
	 */
	public static void downloadExcel(HSSFWorkbook wb, HttpServletResponse res, String fileName) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		wb.write(os);
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		res.reset();
		res.setContentType("application/vnd.ms-excel;charset=utf-8");
		res.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = res.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}

	/**
	 * 
	 * @Description : CSV文件导出
	 * @author zealot
	 * @param @param
	 *            bt
	 * @param @param
	 *            response
	 * @param @param
	 *            fileName
	 * @param @throws
	 *            IOException
	 * @return void
	 * @version 创建时间 : 2016年11月16日 上午11:08:48
	 * @thorws
	 */
	public static void downloadCSV(byte[] bt, HttpServletResponse response, String fileName) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		byte[] content = bt;
		InputStream is = new ByteArrayInputStream(content);
		response.reset();
		response.setContentType("application/csv;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".csv").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);

			byte[] buff = new byte[2048];

			int bytesRead;

			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}

	}

	/**
	 * 
	 * @Description : 导出pdf
	 * @author zealot
	 * @param @param
	 *            list
	 * @param @param
	 *            response
	 * @param @param
	 *            fileName
	 * @param @param
	 *            t
	 * @param @throws
	 *            IOException
	 * @param @throws
	 *            NoSuchMethodException
	 * @param @throws
	 *            SecurityException
	 * @param @throws
	 *            IllegalAccessException
	 * @param @throws
	 *            IllegalArgumentException
	 * @param @throws
	 *            InvocationTargetException
	 * @param @throws
	 *            InstantiationException
	 * @param @throws
	 *            DocumentException
	 * @return void
	 * @version 创建时间 : 2016年11月16日 下午6:04:18
	 * @thorws
	 */
	public static void downloadPDF(List<? extends BaseModel> list, HttpServletResponse response, String fileName,
			Class t) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, InstantiationException, DocumentException {
		String path = PDFUtil.productPDF(list, response, t.newInstance());
		String filepath = path;
		OutputStream os = null;
		BufferedInputStream input = null;
		File file =null;
		try{
			response.setContentType("application/pdf");
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName+".pdf").getBytes(), "iso-8859-1"));
			file = new File(path);  
			FileInputStream is =  new FileInputStream(file);
			input = new BufferedInputStream(is);
			byte buffBytes[] = new byte[2048];
			os = response.getOutputStream();
			int read = 0;
			while ((read = input.read(buffBytes)) != -1) {
				os.write(buffBytes, 0, read);
			}
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			if(os!=null){
				os.flush();
				os.close();
			}
			if(input!=null)
			input.close();
			if(file.exists())
				file.delete();
		}
		
	}
	
	/**
	 * 
	 * @Description : 通用pdf文件导出
	 * @author zealot
	 * @param @param list
	 * @param @param response
	 * @param @param fileName
	 * @param @param t
	 * @param @throws IOException
	 * @param @throws NoSuchMethodException
	 * @param @throws SecurityException
	 * @param @throws IllegalAccessException
	 * @param @throws IllegalArgumentException
	 * @param @throws InvocationTargetException
	 * @param @throws InstantiationException
	 * @param @throws DocumentException
	 * @return void
	 * @version 创建时间 : 2016年11月22日 下午6:11:40
	 * @thorws
	 */
	public static void downloadPublicPDF(List<? extends BaseModel> list, HttpServletResponse response, String fileName,
			Class t) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, InstantiationException, DocumentException {
		String path = PDFUtil.productPublicPDF(list, response, t.newInstance());
		String filepath = path;
		OutputStream os = null;
		BufferedInputStream input = null;
		File file =null;
		try{
			response.setContentType("application/pdf");
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName+".pdf").getBytes(), "iso-8859-1"));
			file = new File(path);  
			FileInputStream is =  new FileInputStream(file);
			input = new BufferedInputStream(is);
			byte buffBytes[] = new byte[2048];
			os = response.getOutputStream();
			int read = 0;
			while ((read = input.read(buffBytes)) != -1) {
				os.write(buffBytes, 0, read);
			}
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			if(os!=null){
				os.flush();
				os.close();
			}
			if(input!=null)
			input.close();
			if(file.exists())
				file.delete();
		}
		
	}
}